package com.robot.agent.controller;

import com.alibaba.fastjson.JSON;
import com.robot.agent.client.MerchantClient;
import com.robot.agent.client.OrdersClient;
import com.robot.agent.pojo.Agent;
import com.robot.agent.pojo.client.Confirmation;
import com.robot.agent.pojo.client.Store;
import com.robot.agent.service.AgentService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 采购付款凭证
 *
 * @@author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/confirmation")
public class ConfirmationController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AgentService agentService;
    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private OrdersClient ordersClient;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CheckUtil checkUtil;

    /**
     * agent表status状态 0-禁用 1-启用
     */
    private String agentStatusEnable = "1";

    /**
     * store表status状态 0-禁用 1-启用
     */
    private String storeStatusEnable = "1";
    /**
     * confirmation表status状态0-待确认 1-已确认 2-驳回
     */
    private String confirmationStatusEnable = "1";

    /**
     * 申请采购付款凭证
     *
     * @param confirmation
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public Result addConfirmation(@RequestBody Confirmation confirmation) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        Agent agentInDb = agentService.findById(claims.getId());
        logger.info("agentInDb=" + agentInDb);
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        String storePhone = confirmation.getStorePhone();
        logger.info("phone=" + storePhone);
        if (storePhone == null || "".equals(storePhone)) {
            return new Result(StatusCode.ERROR_PHONE_REQUIRED);
        }
        if (!checkUtil.checkPhone(storePhone)) {
            return new Result(StatusCode.ERROR_INVALID_PHONE);
        }
        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreByPhone(storePhone), Store.class);
        logger.info("storeInDb=" + storeInDb);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR_MERCHANT_PHONE_NOT_EXIST, "找不到绑定该手机号的商家");
        }
        if (!storeStatusEnable.equals(storeInDb.getStatus())) {
            return new Result(StatusCode.ERROR_MERCHANT_DISABLED, "绑定该手机号的商家被禁用");
        }


        String imagePath = confirmation.getVoucherImage();
        logger.info("imagePath=" + imagePath);
        if (!checkUtil.checkImage(imagePath)) {
            return new Result(StatusCode.ERROR_FILE_FORMAT);
        }

        if (confirmation.getSellingPrice() == null || "".equals(confirmation.getSellingPrice())) {
            return new Result(StatusCode.ERROR_PAY_AMOUNT_REQUIRED);
        }
        if (confirmation.getFacePrice() == null || "".equals(confirmation.getFacePrice())) {
            return new Result(StatusCode.ERROR_FACE_PRICE_REQUIRED);
        }

        //新增采购付款凭证申请
        addConfirmation(confirmation, agentInDb, storeInDb, storePhone);
        return new Result(StatusCode.SUCCESS_APPLY);
    }

    /**
     * 修改采购付款凭证
     *
     * @param confirmation
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public Result updateConfirmation(@RequestBody Confirmation confirmation, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        String agentId = claims.getId();
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        //判断采购付款凭证是否存在,状态是否正常,是否属于该代理商
        Confirmation confirmationInDb = JSON.parseObject(ordersClient.thirdFindConfirmationById(id), Confirmation.class);
        if (confirmationInDb == null || !confirmationInDb.getAgentId().equals(agentId)) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        if (confirmationStatusEnable.equals(confirmationInDb.getStatus())) {
            return new Result(StatusCode.ERROR, "该凭证审核已经通过了");
        }

        String imagePath = confirmation.getVoucherImage();
        if (imagePath != null && !"".equals(imagePath)) {
            logger.info("imagePath=" + imagePath);
            if ("".equals(imagePath)) {
                return new Result(StatusCode.ERROR_FILE_FORMAT);
            }
            confirmationInDb.setVoucherImage(imagePath);
        }

        if (confirmation.getSellingPrice() != null && !"".equals(confirmation.getSellingPrice())) {
            confirmationInDb.setSellingPrice(confirmation.getSellingPrice());
        }
        if (confirmation.getFacePrice() != null && !"".equals(confirmation.getFacePrice())) {
            confirmationInDb.setFacePrice(confirmation.getFacePrice());
        }
        BigDecimal divide = confirmationInDb.getSellingPrice().divide(confirmationInDb.getFacePrice(), 2, RoundingMode.HALF_UP);
        confirmationInDb.setRate(divide.doubleValue());
        confirmationInDb.setStatus("0");

        ordersClient.thirdUpdateConfirmation(JSON.toJSONString(confirmationInDb));
        return new Result(StatusCode.SUCCESS_APPLY);
    }

    /**
     * 采购付款凭证列表
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "{page}/{size}", method = RequestMethod.GET)
    public Result findConfirmations(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(ordersClient.thirdFindConfirmationsByAgentIdOrderByCreatedAt(claims.getId(), page, size)));
    }

    /**
     * 根据status查询采购付款凭证列表
     *
     * @param status
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "{status}/{page}/{size}", method = RequestMethod.GET)
    public Result findConfirmations(@PathVariable String status, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(ordersClient.thirdFindConfirmationsByAgentIdAndStatusOrderByCreatedAt(claims.getId(), status, page, size)));
    }


    /**
     * id查询采购付款凭证申请
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public Result findConfirmation(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Confirmation confirmationInDb = JSON.parseObject(ordersClient.thirdFindConfirmationById(id), Confirmation.class);
        if (confirmationInDb == null || !confirmationInDb.getAgentId().equals(claims.getId())) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, confirmationInDb);
    }

    /**
     * 新增采购付款凭证申请
     *
     * @param confirmation
     * @param agentInDb
     * @param storeInDb
     * @param storePhone
     */
    public void addConfirmation(Confirmation confirmation, Agent agentInDb, Store storeInDb, String storePhone) {
        confirmation.setAgentId(agentInDb.getId());
        confirmation.setAgentName(agentInDb.getRealName());
        confirmation.setAgentPhone(agentInDb.getPhone());
        confirmation.setArea(agentInDb.getArea());
        confirmation.setStorePhone(storePhone);
        confirmation.setCompanyId(storeInDb.getCompanyId());
        confirmation.setStoreId(storeInDb.getId());
        confirmation.setStoreName(storeInDb.getStoreName());
        BigDecimal divide = confirmation.getSellingPrice().divide(confirmation.getFacePrice(), 2, RoundingMode.HALF_UP);
        confirmation.setRate(divide.doubleValue());

        ordersClient.thirdAddConfirmation(JSON.toJSONString(confirmation));
    }
}
